<template>
  <div class="equipment-container">
    <!-- 搜索和操作区域 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.name" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="searchForm.type" placeholder="请选择设备类型" clearable>
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态">
          <el-select v-model="searchForm.status" placeholder="请选择使用状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="operation-btns">
        <el-button type="primary" @click="handleAdd">新增设备</el-button>
        <el-button type="success" @click="handleImport">导入</el-button>
        <el-button type="warning" @click="handleExport">导出</el-button>
      </div>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="设备编号" width="120" />
        <el-table-column prop="name" label="设备名称" width="150" />
        <el-table-column prop="type" label="设备类型" width="120">
          <template #default="scope">
            {{ getTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="model" label="规格型号" width="120" />
        <el-table-column prop="manufacturer" label="生产厂家" width="150" />
        <el-table-column prop="purchaseDate" label="购买日期" width="120" />
        <el-table-column prop="price" label="设备价格" width="120">
          <template #default="scope">
            {{ scope.row.price ? `¥${scope.row.price}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="department" label="使用部门" width="120" />
        <el-table-column prop="status" label="使用状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastMaintenance" label="上次维护时间" width="150" />
        <el-table-column prop="nextMaintenance" label="下次维护时间" width="150" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <!-- <el-button link type="primary" @click="handleMaintenance(scope.row)">维护记录</el-button> -->
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 新增/编辑设备对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增设备' : '编辑设备'"
      width="650px"
      append-to-body
    >
      <el-form
        ref="equipmentFormRef"
        :model="equipmentForm"
        :rules="equipmentRules"
        label-width="100px"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="equipmentForm.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="equipmentForm.type" placeholder="请选择设备类型">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号" prop="model">
          <el-input v-model="equipmentForm.model" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="equipmentForm.manufacturer" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="购买日期" prop="purchaseDate">
          <el-date-picker
            v-model="equipmentForm.purchaseDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="设备价格" prop="price">
          <el-input-number v-model="equipmentForm.price" :precision="2" :step="100" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="使用部门" prop="department">
          <el-input v-model="equipmentForm.department" placeholder="请输入使用部门" />
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="equipmentForm.status" placeholder="请选择使用状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备描述" prop="description">
          <el-input v-model="equipmentForm.description" type="textarea" rows="3" placeholder="请输入设备描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 设备类型选项
const typeOptions = [
  { value: '1', label: '计量设备' },
  { value: '2', label: '检测设备' },
  { value: '3', label: '实验设备' },
  { value: '4', label: '办公设备' },
  { value: '5', label: '其他设备' }
]

// 使用状态选项
const statusOptions = [
  { value: '1', label: '在用' },
  { value: '2', label: '闲置' },
  { value: '3', label: '维修中' },
  { value: '4', label: '报废' }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const equipmentFormRef = ref(null)
const equipmentForm = reactive({
  id: '',
  name: '',
  type: '',
  model: '',
  manufacturer: '',
  purchaseDate: '',
  price: 0,
  department: '',
  status: '1',
  description: ''
})

// 表单验证规则
const equipmentRules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  model: [{ required: true, message: '请输入规格型号', trigger: 'blur' }],
  manufacturer: [{ required: true, message: '请输入生产厂家', trigger: 'blur' }],
  status: [{ required: true, message: '请选择使用状态', trigger: 'change' }]
}

// 获取设备类型名称
const getTypeName = (type) => {
  const found = typeOptions.find(item => item.value === type)
  return found ? found.label : '-'
}

// 获取状态名称
const getStatusName = (status) => {
  const found = statusOptions.find(item => item.value === status)
  return found ? found.label : '-'
}

// 获取状态对应的标签类型
const getStatusType = (status) => {
  switch (status) {
    case '1': return 'success'
    case '2': return 'info'
    case '3': return 'warning'
    case '4': return 'danger'
    default: return 'info'
  }
}

// 查询
const handleSearch = () => {
  fetchData()
}

// 重置查询
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchData()
}

// 获取数据
const fetchData = () => {
  loading.value = true
  // 这里应该调用后端API获取数据
  // 模拟数据
  setTimeout(() => {
    tableData.value = [
      {
        id: 'EQ20230001',
        name: '电子天平',
        type: '1',
        model: 'XYZ-100',
        manufacturer: '上海仪器厂',
        purchaseDate: '2023-01-15',
        price: 12500,
        department: '计量科',
        status: '1',
        lastMaintenance: '2023-06-15',
        nextMaintenance: '2023-12-15',
        description: '高精度电子天平'
      },
      {
        id: 'EQ20230002',
        name: '分光光度计',
        type: '2',
        model: 'UV-2000',
        manufacturer: '北京光学仪器厂',
        purchaseDate: '2022-11-20',
        price: 35000,
        department: '检测科',
        status: '2',
        lastMaintenance: '2023-05-20',
        nextMaintenance: '2023-11-20',
        description: '用于光谱分析'
      },
      {
        id: 'EQ20230003',
        name: '气相色谱仪',
        type: '3',
        model: 'GC-2020',
        manufacturer: '广州分析仪器厂',
        purchaseDate: '2022-08-10',
        price: 85000,
        department: '实验室',
        status: '3',
        lastMaintenance: '2023-02-10',
        nextMaintenance: '2023-08-10',
        description: '用于化合物分析'
      }
    ]
    total.value = 3
    loading.value = false
  }, 500)
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增设备
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑设备
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetForm()
  // 填充表单
  Object.keys(equipmentForm).forEach(key => {
    if (key in row) {
      equipmentForm[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 查看详情
const handleDetail = (row) => {
  ElMessage.info(`查看设备详情：${row.name}`)
}

// 维护记录
const handleMaintenance = (row) => {
  ElMessage.info(`查看维护记录：${row.name}`)
}

// 删除设备
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除设备 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 调用删除API
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    // 取消删除
  })
}

// 导入
const handleImport = () => {
  ElMessage.info('导入设备数据')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出设备数据')
}

// 重置表单
const resetForm = () => {
  if (equipmentFormRef.value) {
    equipmentFormRef.value.resetFields()
  }
  equipmentForm.id = ''
  equipmentForm.name = ''
  equipmentForm.type = ''
  equipmentForm.model = ''
  equipmentForm.manufacturer = ''
  equipmentForm.purchaseDate = ''
  equipmentForm.price = 0
  equipmentForm.department = ''
  equipmentForm.status = '1'
  equipmentForm.description = ''
}

// 提交表单
const submitForm = () => {
  equipmentFormRef.value.validate((valid) => {
    if (valid) {
      // 调用API保存数据
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      ElMessage.success(message)
      dialogVisible.value = false
      fetchData()
    } else {
      return false
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
.equipment-container {
  padding: 20px;
  
  .search-bar {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    
    .search-form {
      margin-bottom: 20px;
    }
    
    .operation-btns {
      display: flex;
      gap: 10px;
    }
  }
  
  .table-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>